 /* 
  Copyright Software Engineering Research laboratory <serl@cs.wichita.edu>

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU Library General Public
 License as published by the Free Software Foundation; either
 version 2 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Library General Public License for more details.

 You should have received a copy of the GNU Library General Public
 License along with this program; if not, write to the Free
 Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
 */
package wichita.edu.utility;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
 * @author: Sara Bahrami <mxbahramizanjani@wichita.edu>
 * class for converting source code to XML. Running src2srcml
 */
public class SrcML {
    public static File wd = new File("/usr/bin/");
	//source code repository path
	public static  String sourceCodeDirPath ="/home/sara/research/codereview/Mylyn/Repository/Myly-complete";
	public static  String outputDirPath = "/home/sara/research/codereview/Mylyn/Repository/Srcml";
    public static void main(String[] args) {

        File folder = new File(sourceCodeDirPath);
        //RemoveTestFiles(folder);
        listFilesForFolder(folder);}
    
  
    /*
     * This method removes all test files and example files from the source code repository of project
     */
    /* 
 
   public static void RemoveTestFiles(final File folder) {
        int count=0;
    
    Pattern pattern=Pattern.compile("[a-zA-Z_0-9]*(Test)[a-zA-Z_0-9]*");
    //Pattern pattern1=Pattern.compile("[a-zA-Z_0-9]*[-](examples)[a-zA-Z_0-9]*");
        
     for (final File fileEntry : folder.listFiles()) {
       if (fileEntry.isDirectory()) {
         listFilesForFolder(fileEntry);
       } else {
         if (fileEntry.isFile())
         {   
             Matcher matcher = pattern.matcher(fileEntry.getName());
             //Matcher matcher1 = pattern1.matcher(fileEntry.getName());
             if ((FileType(fileEntry.getName())==true)&&(matcher.find()))
                 {System.out.println(fileEntry.getAbsolutePath());
                     fileEntry.delete();
                 count=count+1;}
             //converttoSrcXml(fileEntry.getAbsolutePath());
            
         }
     }
 }
     System.out.println(count);
 }
   */
    
    
    
    /*
     * walking trough source code repository
     */
    public static void listFilesForFolder(final File folder) {

        for (final File fileEntry : folder.listFiles()) {
          if (fileEntry.isDirectory()) {
            listFilesForFolder(fileEntry);
          } else {
            if (fileEntry.isFile())
            {	if (FileType(fileEntry.getName())==true)
            	converttoSrcXml(fileEntry.getAbsolutePath());}
        }
    }
    }
     /*
      * Finding just Java files 
      */
        public static boolean FileType(final String fileName) {

            Pattern pattern = Pattern.compile("([^\\s]+(\\.(?i)(java))$)");
            Matcher matcher = pattern.matcher(fileName); 
                return matcher.matches();

            }
     /*
      * running src2srcml command for each file and save the XML out put in directory    
      */
     private static void converttoSrcXml(String srcPath) {
    	
    	Process proc = null;
        String outPutXmlFilePath = "";
        try {
            proc = Runtime.getRuntime().exec("/bin/bash", null, wd);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (proc != null) {
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    proc.getInputStream()));
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(proc.getOutputStream())), true);
            File srcFile = new File(srcPath);
            String name=Pathcreator(srcFile.getAbsolutePath());
            //String name=srcFile.getName();
            System.out.println(name);
            outPutXmlFilePath = outputDirPath+"/" +name;

            String cmd = "src2srcml" + " " + srcPath + " " + "-o " + outPutXmlFilePath;
           // System.out.println(cmd);
            out.println(cmd);
            out.println("exit");
            try {
                String line;
                while ((line = in.readLine()) != null) {
                    System.out.println(line);
                }
                proc.waitFor();
                in.close();
                out.close();
                proc.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
 
       
    }
    
    /*
     * Returning the absolute path of file as name string with - instead of /  and removing all the path before "org" 
     * from the string name.
     */
    private static String Pathcreator(String path){
    	int startIndex1=path.indexOf("org");
		path=path.substring(startIndex1);
		path=path.replace('/','-' );
		return path;
		
    }

}
